//
//  XMRegistOneViewController.m
//  XunMi
//
//  Created by MacBook on 2024/2/22.
//  Copyright © 2024 TieZhu. All rights reserved.
//

#import "XMRegistThreeViewController.h"
#import <TZImagePickerController.h>
#import "XMChooseHeadTipView.h"

@interface XMRegistThreeViewController () <TZImagePickerControllerDelegate, UIImagePickerControllerDelegate, UINavigationControllerDelegate>
@property (weak, nonatomic) IBOutlet UIButton *chooseButton;
@property (nonatomic, strong) XMChooseHeadTipView *tipView;
@property (nonatomic, strong) UIImage *headImg;
@property (weak, nonatomic) IBOutlet UILabel *manTipLa;

@end

@implementation XMRegistThreeViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.navView.backgroundColor = kHEXA(@"ffffff", 0);
    self.view.backgroundColor = kHEX(@"#F2F2F2");
    [self.navRightBtn setTitle:@"3/3" forState:UIControlStateNormal];
    [self.navRightBtn setTitleColor:kAppMainColor forState:UIControlStateNormal];
    self.tipView = [XMChooseHeadTipView viewFromXib];
    self.tipView.size = CGSizeMake(kScreenWidth, kScreenHeight);
    
    self.manTipLa.text = kStringFormat(@"*注册成功送免费聊天卡%ld张", kGlobalVariables.appConfig.man_free_chat);
    self.manTipLa.hidden = [self.gender isEqualToString:@"2"];
    
    XMWeakSelf(self);
    [self.tipView actionTakeBlock:^{
        XMStrongSelf(self);
        [self takePhoto];
    } chooseBlock:^{
        XMStrongSelf(self);
        [self chooseHeadImg];
    } cancelBlock:^{
        [GKCover hideCover];
    }];
}

- (void)takePhoto {
    if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera]) {
        UIImagePickerController *imagePicker = [[UIImagePickerController alloc] init];
        imagePicker.delegate = self;
        imagePicker.sourceType = UIImagePickerControllerSourceTypeCamera;
        [self presentViewController:imagePicker animated:YES completion:nil];
    } else {
        NSLog(@"Camera is not available.");
    }
}

- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary<UIImagePickerControllerInfoKey, id> *)info {
    UIImage *image = info[UIImagePickerControllerOriginalImage];
    self.headImg = image;
    [self.chooseButton setImage:image forState:UIControlStateNormal];
    [picker dismissViewControllerAnimated:YES completion:nil];
    [GKCover hideCover];
}

- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker {
    [picker dismissViewControllerAnimated:YES completion:nil];
}


- (void)showTipView {
    [GKCover coverFrom:self.view contentView:self.tipView style:(GKCoverStyleTranslucent) showStyle:(GKCoverShowStyleCenter) showAnimStyle:(GKCoverShowAnimStyleNone) hideAnimStyle:(GKCoverHideAnimStyleNone) notClick:YES];
    
}

- (IBAction)chooseAct:(UIButton *)sender {
    [self showTipView];
}

- (IBAction)openAct:(UIButton *)sender {
//    if (_headImg == nil) {
//        [MBProgressHUD showHUDMsg:@"请选择头像!" toView:nil];
//        return;
//    }
    
    __block NSString *voiceJson = @"";
    __block NSString *imageJson = @"";
    [MBProgressHUD showHUDActivityMsg:nil toView:kWindow];
    if (self.recordTime > 0) {
        if (_headImg == nil) {
            [[XMUploadManager sharedInstance] uploadWithFilePath:self.recordPath type:XMUploadTypeAudio person_id:self.person_id complete:^(XMUploadResultModel * _Nonnull result) {
                if (result.success) {
                    NSMutableDictionary *dic = [XMUploadResultModel paramDic:result fileType:@"2"];
                    [dic setObject:@(self.recordTime) forKey:@"voice_length"];
                    voiceJson = [dic jsonStringEncoded];
                    [self finallyRegist:imageJson voiceJson:voiceJson];
                } else {
                    [MBProgressHUD hideHUD];
                    [MBProgressHUD showHUDMsg:@"录音上传失败请重试!" toView:nil];
                }
            }];
        } else {
            
            dispatch_group_t group = dispatch_group_create();
            
            dispatch_group_enter(group);
            [[XMUploadManager sharedInstance] uploadWithFilePath:self.recordPath type:XMUploadTypeAudio person_id:self.person_id complete:^(XMUploadResultModel * _Nonnull result) {
                if (result.success) {
                    NSMutableDictionary *dic = [XMUploadResultModel paramDic:result fileType:@"2"];
                    [dic setObject:@(self.recordTime) forKey:@"voice_length"];
                    voiceJson = [dic jsonStringEncoded];
                    dispatch_group_leave(group);
                } else {
                    [MBProgressHUD hideHUD];
                    [MBProgressHUD showHUDMsg:@"录音上传失败请重试!" toView:nil];
                }
            }];
            
            
            
            dispatch_group_enter(group);
            [[XMUploadManager sharedInstance] uploadImage:self.headImg compress:NO person_id:self.person_id complete:^(XMUploadResultModel * _Nonnull result) {
                if (result.success) {
                    imageJson = [[XMUploadResultModel paramDic:result fileType:@"1"] jsonStringEncoded];
                    dispatch_group_leave(group);
                } else {
                    [MBProgressHUD hideHUD];
                    [MBProgressHUD showHUDMsg:@"图片上传失败请重试!" toView:nil];
                }
            }];
            
            dispatch_group_notify(group, dispatch_get_main_queue(), ^{
                [self finallyRegist:imageJson voiceJson:voiceJson];
            });
        }
        
        
        
    } else {
        if (_headImg == nil) {
            [self finallyRegist:imageJson voiceJson:voiceJson];
        } else {
            [[XMUploadManager sharedInstance] uploadImage:self.headImg compress:NO person_id:self.person_id complete:^(XMUploadResultModel * _Nonnull result) {
                if (result.success) {
                    imageJson = [[XMUploadResultModel paramDic:result fileType:@"1"] jsonStringEncoded];
                    [self finallyRegist:imageJson voiceJson:voiceJson];
                }
            }];
        }
        
    }
    
    
    
//    [[AppDelegate sharedAppDelegate] configureIMAndEnterHomeIfNeed];
}

- (void)finallyRegist:(NSString *)imageJson voiceJson:(NSString *)voiceJson {
    [MBProgressHUD showHUDActivityMsg:nil toView:kWindow];
    NSMutableDictionary *dic = @{}.mutableCopy;
    [dic setObject:[NSString xm_stringNoNullWith:self.person_id] forKey:@"person_id"];
    [dic setObject:[NSString xm_stringNoNullWith:self.content] forKey:@"content"];
    [dic setObject:[NSString xm_stringNoNullWith:self.age] forKey:@"age"];
    [dic setObject:[NSString xm_stringNoNullWith:imageJson] forKey:@"avatar"];
    [dic setObject:[NSString xm_stringNoNullWith:self.gender] forKey:@"gender"];
    [dic setObject:[NSString xm_stringNoNullWith:self.nickname] forKey:@"nickname"];
    [dic setObject:[NSString xm_stringNoNullWith:self.shengao] forKey:@"height"];
    [dic setObject:[NSString xm_stringNoNullWith:self.tizhong] forKey:@"weight"];
    [dic setObject:[NSString xm_stringNoNullWith:self.xueli] forKey:@"education"];
    [dic setObject:[NSString xm_stringNoNullWith:self.zhiye] forKey:@"occupation"];
    [dic setObject:[NSString xm_stringNoNullWith:self.city] forKey:@"province"];
    [dic setObject:[NSString xm_stringNoNullWith:self.sign] forKey:@"text_intro"];
    [dic setObject:[NSString xm_stringNoNullWith:voiceJson] forKey:@"voice_intro"];
    [dic setObject:[NSString xm_stringNoNullWith:self.invite_code] forKey:@"invite_code"];
    [dic setObject:[NSString xm_stringNoNullWith:[kMMKV getStringForKey:@"idfa"]] forKey:@"idfa"];

    XMLog(@"%@", dic);
    [YHNetworkManager.sharedInstance postWithUrl:@"api/auth/register" parameters:dic completeBlock:^(XMResponseTip * _Nonnull tip, id  _Nullable result) {
        if (tip.success) {
            [MBProgressHUD hideHUD];
            XMUserModel *model = [XMUserModel  mj_objectWithKeyValues:result];
            [[XMLoginManager sharedInstance] doLoginResult:model];
        }
    }];
    
}

- (void)chooseHeadImg {
    TZImagePickerController *imagePicker = [[TZImagePickerController alloc] initWithMaxImagesCount:1 columnNumber:4 delegate:self pushPhotoPickerVc:YES];
    imagePicker.isSelectOriginalPhoto = NO;
    imagePicker.allowTakeVideo = NO;
    imagePicker.allowPickingVideo = NO;
    imagePicker.allowTakePicture = NO;
    [imagePicker setUiImagePickerControllerSettingBlock:^(UIImagePickerController *imagePickerController) {
        imagePickerController.videoQuality = UIImagePickerControllerQualityTypeHigh;
    }];
    imagePicker.navigationBar.barTintColor = UIColor.whiteColor;
    imagePicker.oKButtonTitleColorNormal = kAppMainColor;
    imagePicker.oKButtonTitleColorDisabled = kAppMainColor;
    imagePicker.barItemTextColor = UIColor.blackColor;
    imagePicker.navigationBar.translucent = NO;
    [imagePicker.navigationBar setTitleTextAttributes:@{NSForegroundColorAttributeName: [UIColor blackColor]}];
    imagePicker.navigationBar.tintColor = UIColor.blackColor;
    if (@available(iOS 13.0, *)) {
        UINavigationBarAppearance *barAppearance = [[UINavigationBarAppearance alloc] init];
        barAppearance.backgroundColor = imagePicker.navigationBar.barTintColor;
        barAppearance.titleTextAttributes = imagePicker.navigationBar.titleTextAttributes;
        imagePicker.navigationBar.standardAppearance = barAppearance;
        imagePicker.navigationBar.scrollEdgeAppearance = barAppearance;
    }
    imagePicker.iconThemeColor = kAppMainColor;
    imagePicker.showPhotoCannotSelectLayer = YES;
    imagePicker.cannotSelectLayerColor = [[UIColor whiteColor] colorWithAlphaComponent:0.8];
    [imagePicker setPhotoPickerPageUIConfigBlock:^(UICollectionView *collectionView, UIView *bottomToolBar, UIButton *previewButton, UIButton *originalPhotoButton, UILabel *originalPhotoLabel, UIButton *doneButton, UIImageView *numberImageView, UILabel *numberLabel, UIView *divideLine) {
        [previewButton setTitleColor:kAppMainColor forState:UIControlStateNormal];
        [originalPhotoButton setImage:kGetImage(@"ic_dyn_origin_s") forState:UIControlStateSelected];
    }];
    [imagePicker setNavLeftBarButtonSettingBlock:^(UIButton *leftButton) {
        [leftButton setImage:[UIImage imageNamed:@"xm_arrow_back"] forState:UIControlStateNormal];
        [leftButton setImageEdgeInsets:UIEdgeInsetsMake(0, -10, 0, 20)];
    }];
    imagePicker.statusBarStyle = UIStatusBarStyleDefault;
    imagePicker.showSelectedIndex = YES;
    imagePicker.sortAscendingByModificationDate = NO;
    imagePicker.showSelectBtn = NO;
    imagePicker.allowCrop = YES;
    imagePicker.needCircleCrop = NO;
    NSInteger left = 10;
    NSInteger widthHeight = self.view.width - 2 * left;
    NSInteger top = (self.view.height - widthHeight) / 2;
    if ([TZCommonTools tz_isLandscape]) {
        top = 10;
        widthHeight = self.view.height - 2 * left;
        left = (self.view.width - widthHeight) / 2;
    }
    imagePicker.cropRect = CGRectMake(left, top, widthHeight, widthHeight);
    imagePicker.scaleAspectFillCrop = YES;
    imagePicker.modalPresentationStyle = UIModalPresentationFullScreen;
    [self presentViewController:imagePicker animated:YES completion:nil];
}

#pragma mark - TZImagePickerControllerDelegate
- (void)tz_imagePickerControllerDidCancel:(TZImagePickerController *)picker {
}
- (void)imagePickerController:(TZImagePickerController *)picker didFinishPickingPhotos:(NSArray<UIImage *> *)photos sourceAssets:(NSArray *)assets isSelectOriginalPhoto:(BOOL)isSelectOriginalPhoto infos:(NSArray<NSDictionary *> *)infos {
    if (photos.count > 0) {
        self.headImg = [photos firstObject];
        [self.chooseButton setImage:[photos firstObject] forState:UIControlStateNormal];
        [GKCover hideCover];
        //        [MBProgressHUD showHUDActivityMsg:nil toView:kWindow];
//        [[YHUploadManager sharedInstance] uploadImage:[photos firstObject]
//                                             compress:YES
//                                                 head:YES
//                                            prepareId:@""
//                                             complete:^(YHUploadResultModel *_Nonnull model) {
//            NSString *imageJson = [[YHUploadResultModel paramDic:model] jsonStringEncoded];
//            XMWeakSelf(self);
//            [self updateUserInfoType:YHUserEditTypeHeader
//                             content:imageJson
//                       completeBlock:^(YHResponseTip *_Nonnull tip, id _Nullable result) {
//                XMStrongSelf(self);
//                if (tip.success) {
//                    self.headImgView.image = [photos firstObject];
//                    self.headStateLa.hidden = NO;
//                    kUserModel.avatar_status = 1;
//                    kUserModel.avatar.file_url = model.url;
//                }
//            }];
//        }];
    }
}
@end
